package com.peng._07springaop.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 切面类
 * 作用：为目标方法进行功能增强的类
 *
 * @Author peng
 * @Date 2024-04-29 9:35
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    /**
     * 前置通知
     * @param joinPoint 连接点
     */
    @Before("execution(* com.peng._07springaop.aop.CalculatorImpl.*(..))")
    public void beforeMethod(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("[开始日志]：{}方法开始执行", joinPoint.getSignature().getName());
        log.info("[开始日志]：方法参数为：{}", Arrays.stream(joinPoint.getArgs())
                .map(Object::toString)
                .collect(Collectors.joining(",")));
    }

    /**
     * 方法执行完返回通知
     * @param joinPoint 连接点
     * @param result 方法返回对象
     */
    @AfterReturning(value = "execution(* com.peng._07springaop.aop.CalculatorImpl.*(..))",
            returning = "result")
    public void afterMethod(JoinPoint joinPoint, Object result) {
        log.info("[结束日志]：{}方法执行结束，结果为：{}", joinPoint.getSignature().getName(), result);
    }

    /**
     * 方法执行异常通知
     * @param joinPoint 连接点
     * @param e 异常对象
     */
    @AfterThrowing(value = "execution(* com.peng._07springaop.aop.CalculatorImpl.*(..))",throwing = "e")
    public void afterThrowingMethod(JoinPoint joinPoint, Throwable e) {
        log.info("[异常日志]：{}方法执行异常，异常类型为：{}", joinPoint.getSignature().getName(), e.getMessage());
    }

    /**
     * 方法执行完最终通知
     * 后置通知，方法彻底执行结束（正常结束和异常结束）后执行
     * @param joinPoint 连接点
     */
    @After(value = "execution(* com.peng._07springaop.aop.CalculatorImpl.*(..))")
    public void afterMethod(JoinPoint joinPoint) {
        log.info("[最终日志]：{}方法执行结束", joinPoint.getSignature().getName());
    }

    /**
     * 环绕通知
     * Around注解：贯穿于整个方法执行过程，可以控制整个方法执行过程
     */
    @Around(value = "execution(* com.peng._07springaop.aop.CalculatorImpl.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) {
        Object result = null;
        try {
            /** 执行流程：
             * 1. 前置通知
             * 2. 执行目标方法
             * 3. 返回通知
             * 4. 有异常则执行异常通知
             * 5. finally中执行后置通知
             */
            log.info("[环绕日志]前置通知: {} 开始执行", joinPoint.getSignature().getName());
            result = joinPoint.proceed();
            log.info("[环绕日志]返回通知: {} 执行结束", joinPoint.getSignature().getName());
        } catch (Throwable e) {
            log.info("[环绕日志]异常通知，异常类型：{}", e.getMessage());
            throw new RuntimeException("环绕通知异常");
        } finally {
            log.info("[环绕日志]最终通知: {} 执行结束", joinPoint.getSignature().getName());
        }
        return result;
    }

}
